package com.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.bean.ImageContext;
import com.bean.ImageHostness;
import com.bean.ZanMessage;
import com.dao.ImageContextDao;
import com.util.CodeUtil;
import com.util.Domain;
import com.util.ImgmanagesIndexUtil;
import com.util.LoggerUtil;
import com.util.Pager;
@Component
public class ImageContextDaoImpl implements ImageContextDao{
	public static Logger logger=Logger.getLogger(ImageContextDaoImpl.class);
	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private ImgmanagesIndexUtil util;
	@Override
	public Pager<ImageContext> selectPageByZanNum(Integer curPage,
			Integer pageSize,String userId) {
		Pager<ImageContext> pager=new Pager<ImageContext>();
		if(curPage!=null)
			pager.setCurPage(curPage);
		if(pageSize!=null)
			pager.setPageSize(pageSize);
		
		List<ImageContext> imgs=mongoTemplate.find(new Query(Criteria.where("rating").is(2)).skip(pager.getStart())
				.limit(pager.getPageSize()).with(new Sort(Sort.Direction.DESC,"publishDate")), ImageContext.class);
		List<Integer> indexes=CodeUtil.randomIndexes1(imgs.size());
		List<ImageContext> data=new ArrayList<>();
		for(Integer index:indexes){
			data.add(imgs.get(index));
		}
		pager.setData(util.addIndexImgmanages(pager.getStart(), data,userId));
		pager.setData(util.addIndexImgmanages(pager.getStart(), data,userId));
		long count=mongoTemplate.count(new Query(Criteria.where("rating").is(2)), ImageContext.class);
		pager.setTotalRow(Integer.valueOf(String.valueOf(count)));
		return pager;
	}
	@Override
	public Pager<ImageContext> selectPageByTag(Integer curPage,
			Integer pageSize,String imgtags,String userId) {
		Pager<ImageContext> pager=new Pager<ImageContext>();
		if(curPage!=null)
			pager.setCurPage(curPage);
		if(pageSize!=null)
			pager.setPageSize(pageSize);
		Query query=new Query();
		if(StringUtils.isNotEmpty(imgtags)){
			Criteria criteria = Criteria.where("tag").in(imgtags);
			query.addCriteria(criteria);
		}
		List<ImageContext> data=mongoTemplate.find(query
		.skip(pager.getStart()).limit(pager.getPageSize()).with(new Sort(Sort.Direction.DESC,"rating"))
		.with(new Sort(Sort.Direction.DESC,"publishDate")), ImageContext.class);
		pager.setData(util.addIndexImgmanages(pager.getStart(), data,userId));
		pager.setData(data);
		long count=mongoTemplate.count(query, ImageContext.class);
		pager.setTotalRow(Integer.valueOf(String.valueOf(count)));
		return pager;
	}
	@Override
	public Map<String, Object> updateZanNum(String id,String user_id){
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			Query zanQuery=new Query(Criteria.where("types")
					.is(Domain.zan_message_types_zan).and("user_id").is(user_id).and("msg_id").is(id).and("is_delete").is(Domain.zan_message_is_delete_n)
					.and("text_types").is(Domain.zan_message_text_types_image));
			List<ZanMessage> zanMessages=mongoTemplate.find(zanQuery, ZanMessage.class);
			if(zanMessages!=null&&zanMessages.size()>0){
				mongoTemplate.updateMulti(zanQuery, new Update().set("is_delete", Domain.zan_message_is_delete_y), ZanMessage.class);
				Query query=new Query(Criteria.where("_id").is(id));
				Update update=new Update();
				update.inc("zanNum2", -1);
				mongoTemplate.findAndModify(query, update, ImageContext.class);
				map.put("code", "107");
				return map;
			}
			Query query=new Query(Criteria.where("_id").is(id));
			Update update=new Update();
			update.inc("zanNum2", 1);
			mongoTemplate.findAndModify(query, update, ImageContext.class);
			//ZanMessage zanMessage=new ZanMessage(Domain.zan_message_text_types_image,user_id,id,Domain.zan_message_is_delete_n,new Date());
			//mongoTemplate.insert(zanMessage);
			map.put("code", "0");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put("code", "101");
		}
		return map;
	}
	@Override
	public Map<String, Object> updateHostness(String id,String userId,JSONObject logs) {
		Map<String, Object> map=new HashMap<>();
		
		try {
			Query query=new Query(Criteria.where("_id").is(id));
			Update update=new Update();
			update.inc("hostness", 1);
			mongoTemplate.findAndModify(query, update,ImageContext.class);
			if(StringUtils.isNotEmpty(userId)){
				ImageHostness hostness=new ImageHostness();
				hostness.setImageId(id);
				hostness.setUserId(userId);
				mongoTemplate.insert(hostness);
			}
			map.put("code", "0");
			LoggerUtil.backlogsSuccess(logs, logger);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put("code", "101");
			LoggerUtil.backlogsFalseError(logs, logger,e);
			return map;
		}
		return map;
	}
	
	
}
